package com.oliver.oliveraiagent.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oliver.oliveraiagent.exception.BusinessException;
import com.oliver.oliveraiagent.exception.ErrorCode;
import com.oliver.oliveraiagent.model.dto.user.UserLoginRequest;
import com.oliver.oliveraiagent.model.dto.user.UserRegisterRequest;
import com.oliver.oliveraiagent.model.entity.User;
import com.oliver.oliveraiagent.model.entity.UserCredits;
import com.oliver.oliveraiagent.model.vo.UserLoginVO;
import com.oliver.oliveraiagent.service.UserCreditsService;
import com.oliver.oliveraiagent.service.UserService;
import com.oliver.oliveraiagent.mapper.UsersMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import static com.oliver.oliveraiagent.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author snow
* @description 针对表【users】的数据库操作Service实现
* @createDate 2025-05-25 17:09:05
*/
@Service
public class UserServiceImpl extends ServiceImpl<UsersMapper, User>
    implements UserService {

    @Resource
    private UserCreditsService userCreditsService;

    /**
     * 用户登录
     *
     * @param loginRequest
     * @param request
     * @return
     */
    @Override
    public UserLoginVO login(UserLoginRequest loginRequest, HttpServletRequest request) {
        //  前置校验
        if (StrUtil.isBlank(loginRequest.getAccount()) || StrUtil.isBlank(loginRequest.getPassword())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"登录账号或密码不能为空");
        }

        //  md5 加密用户密码
        String password = loginRequest.getPassword();

        //  查询
        User user = lambdaQuery()
                .eq(User::getAccount, loginRequest.getAccount())
                .eq(User::getPassword, getEncryptPassword(password))
                .one();

        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号或密码错误");
        }

        request.getSession().setAttribute(USER_LOGIN_STATE, user);
        return this.getLoginUserVO(user);
    }

    /**
     * 用户注册
     * @param registerRequest
     */
    @Override
    public void register(UserRegisterRequest registerRequest) {
        //  前置校验
        if (StrUtil.isBlank(registerRequest.getUserName())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户名不能为空");
        }
        if (StrUtil.isBlank(registerRequest.getAccount())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号不能为空");
        }
        if (StrUtil.isBlank(registerRequest.getPassword())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码不能为空");
        }

        User user = new User();
        user.setUserName(registerRequest.getUserName());
        user.setAccount(registerRequest.getAccount());
        user.setPassword(getEncryptPassword(registerRequest.getPassword()));
        user.setAvatarImg(registerRequest.getAvatarImg());
        user.setEmail(registerRequest.getEmail());

        //  校验用户名
        User one = lambdaQuery().eq(User::getAccount, registerRequest.getAccount())
                .one();
        if (one != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号已存在");
        }

        //  保存
        save(user);

        //  保存用户额度，默认给予100额度
        UserCredits userCredits = new UserCredits();
        userCredits.setUserId(user.getUserId());
        userCredits.setAvailableCredit(100);
        userCredits.setTotalCredit(100);
        userCreditsService.save(userCredits);
    }

    @Override
    public String getEncryptPassword(String userPassword) {
        // 盐值，混淆密码
        final String SALT = "oliver";
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }

    public UserLoginVO getLoginUserVO(User user){
        if (user == null) {
            return null;
        }
        UserLoginVO loginUserVO = new UserLoginVO();
        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    /**
     * 从请求头中的cookie中获取用户
     *
     * @param request
     * @return
     */

    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getUserId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询（追求性能的话可以注释，直接返回上述结果）
        long userId = currentUser.getUserId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }
}




